package com.sh.weblogspringboot.jwt.handler;

import com.sh.weblogspringboot.common.util.Response;
import com.sh.weblogspringboot.jwt.util.JwtTokenHelper;
import com.sh.weblogspringboot.jwt.util.ResultUtil;
import com.sh.weblogspringboot.jwt.vo.LoginRspVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author songHai
 * @Classname RestAuthenticationSuccessHandler
 * @Description
 * @Date 2025/3/26 23:11
 */
@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenHelper jwtTokenHelper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从authentication对象中获取用户的UserDetails实例，这里是获取用户的用户名
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        // 通过用户名生成Token
        String userName = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(userName);

        // 返回Token
        LoginRspVO loginRspVO = LoginRspVO.builder().token(token).build();

        ResultUtil.ok(response, Response.success(loginRspVO));
    }
}
